'use client';

import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { z } from 'zod';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { format } from 'date-fns';
import { useToast } from '@/components/ui/use-toast';
import { Toaster } from 'sonner';
import { cn } from '@/lib/utils';
import { formatDate } from '@/lib/utils';

import {
  Class,
  ClassQueryParams,
  getClasses,
  createClass,
  updateClass,
  deleteClass,
  CreateClassParams,
  UpdateClassParams,
  PageResponse,
  assignTeacherToClass
} from '@/services/classService';

import { getTeacherList, TeacherListItem } from '@/services/teacherService';

import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from '@/components/ui/form';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Switch } from '@/components/ui/switch';
import { FadeIn } from '@/components/ui/motion';
import { RefreshCw, Pencil, Trash, UserPlus } from 'lucide-react';

// 班级表单验证模式
const classFormSchema = z.object({
  name: z.string().min(2, "班级名称至少2个字符").max(50, "班级名称最多50个字符"),
  grade: z.string().min(2, "年级名称至少2个字符").max(50, "年级名称最多50个字符"),
  capacity: z.union([z.string(), z.number()]).optional().transform(val => 
    val === '' ? null : typeof val === 'string' ? parseInt(val, 10) : val
  ),
  currentCount: z.union([z.string(), z.number()]).optional().transform(val => 
    val === '' ? null : typeof val === 'string' ? parseInt(val, 10) : val
  ),
  remarks: z.string().optional(),
  enabled: z.boolean().default(true),
});

type ClassFormValues = z.infer<typeof classFormSchema>;

export default function ClassPage() {
  const router = useRouter();
  const { toast } = useToast();
  const [classes, setClasses] = useState<Class[]>([]);
  const [searchTerm, setSearchTerm] = useState('');
  const [loading, setLoading] = useState(false);
  const [isAddDialogOpen, setIsAddDialogOpen] = useState(false);
  const [isEditDialogOpen, setIsEditDialogOpen] = useState(false);
  const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
  const [isAssignTeacherDialogOpen, setIsAssignTeacherDialogOpen] = useState(false);
  const [selectedClass, setSelectedClass] = useState<Class | null>(null);
  const [teachers, setTeachers] = useState<TeacherListItem[]>([]);
  const [selectedTeacherId, setSelectedTeacherId] = useState<string>('');
  const [pagination, setPagination] = useState({
    page: 0,
    size: 10,
    totalPages: 0,
    totalElements: 0,
    last: true,
    first: true
  });

  // 添加班级表单
  const addForm = useForm<ClassFormValues>({
    resolver: zodResolver(classFormSchema),
    defaultValues: {
      name: '',
      grade: '',
      capacity: null,
      currentCount: null,
      remarks: '',
      enabled: true,
    },
  });

  // 编辑班级表单
  const editForm = useForm<ClassFormValues>({
    resolver: zodResolver(classFormSchema),
    defaultValues: {
      name: '',
      grade: '',
      capacity: null,
      currentCount: null,
      remarks: '',
      enabled: true,
    },
  });

  // 初始加载
  useEffect(() => {
    fetchClasses();
    fetchTeachers();
  }, []);

  // 获取班级列表
  const fetchClasses = async (params: ClassQueryParams = {}) => {
    setLoading(true);
    try {
      const { page = pagination.page, size = pagination.size, keyword = searchTerm } = params;
      const response = await getClasses({ page, size, keyword });
      
      // 检查响应数据结构
      console.log('API 响应:', response);
      
      // 处理API返回的数据结构
      if (response?.content) {
        // 设置班级列表和分页数据
        setClasses(response.content);
        setPagination({
          page: response.pageable.pageNumber,
          size: response.pageable.pageSize,
          totalPages: response.totalPages,
          totalElements: response.totalElements,
          last: response.last,
          first: response.first
        });
      } else {
        console.error('API响应数据格式错误');
        toast({
          title: '数据格式错误',
          description: '服务器返回的数据格式不正确',
          variant: 'destructive',
        });
        setClasses([]);
      }
    } catch (error) {
      console.error('获取班级列表失败:', error);
      toast({
        title: '获取失败',
        description: '无法获取班级列表，请稍后重试',
        variant: 'destructive',
      });
      // 出错时设置空数据
      setClasses([]);
    } finally {
      setLoading(false);
    }
  };

  // 获取教师列表
  const fetchTeachers = async () => {
    try {
      const teacherList = await getTeacherList();
      console.log('获取到的教师列表:', teacherList);
      setTeachers(teacherList);
    } catch (error) {
      console.error('获取教师列表失败:', error);
      toast({
        title: '获取失败',
        description: '无法获取教师列表，请稍后重试',
        variant: 'destructive',
      });
    }
  };

  // 搜索处理
  const handleSearch = () => {
    fetchClasses({ page: 0, keyword: searchTerm });
  };

  // 分页处理
  const handlePageChange = (newPage: number) => {
    fetchClasses({ page: newPage });
  };

  // 添加班级
  const handleAddClass = async (data: ClassFormValues) => {
    setLoading(true);
    try {
      console.log('提交的表单数据:', data);
      
      // 创建班级参数
      const createParams: CreateClassParams = {
        name: data.name,
        grade: data.grade,
        capacity: data.capacity,
        currentCount: data.currentCount,
        remarks: data.remarks
      };
      
      console.log('创建参数:', createParams);
      
      const result = await createClass(createParams);
      
      console.log('添加班级结果:', result);
      
      // 刷新列表
      fetchClasses();
      
      // 关闭对话框并重置表单
      setIsAddDialogOpen(false);
      addForm.reset();
      
      toast({
        title: '添加成功',
        description: `班级 ${data.grade}${data.name} 已成功添加`,
      });
    } catch (error) {
      console.error('添加班级失败:', error);
      toast({
        title: '添加失败',
        description: '班级添加失败，请稍后重试',
        variant: 'destructive',
      });
    } finally {
      setLoading(false);
    }
  };

  // 编辑班级
  const handleEditClass = async (data: ClassFormValues) => {
    if (!selectedClass) return;
    
    setLoading(true);
    try {
      console.log('提交的编辑表单数据:', data);
      
      // 更新班级参数
      const updateParams: UpdateClassParams = {
        name: data.name,
        grade: data.grade,
        capacity: data.capacity,
        currentCount: data.currentCount,
        remarks: data.remarks
      };
      
      console.log('更新参数:', updateParams);
      
      const result = await updateClass(selectedClass.id, updateParams);
      
      console.log('编辑班级结果:', result);
      
      // 刷新列表
      fetchClasses();
      
      // 关闭对话框
      setIsEditDialogOpen(false);
      
      toast({
        title: '更新成功',
        description: `班级 ${data.grade}${data.name} 信息已更新`,
      });
    } catch (error) {
      console.error('编辑班级失败:', error);
      toast({
        title: '更新失败',
        description: '班级信息更新失败，请稍后重试',
        variant: 'destructive',
      });
    } finally {
      setLoading(false);
    }
  };

  // 删除班级
  const handleDeleteClass = async () => {
    if (!selectedClass) return;
    
    setLoading(true);
    try {
      await deleteClass(selectedClass.id);
      
      // 刷新列表
      fetchClasses();
      
      // 关闭对话框
      setIsDeleteDialogOpen(false);
      
      toast({
        title: '删除成功',
        description: `班级 ${selectedClass.grade}${selectedClass.name} 已删除`,
      });
    } catch (error) {
      console.error('删除班级失败:', error);
      toast({
        title: '删除失败',
        description: '班级删除失败，请稍后重试',
        variant: 'destructive',
      });
    } finally {
      setLoading(false);
    }
  };

  // 打开编辑对话框
  const openEditDialog = (classItem: Class) => {
    setSelectedClass(classItem);
    
    console.log('编辑班级信息:', classItem);
    
    // 设置表单默认值
    editForm.reset({
      name: classItem.name,
      grade: classItem.grade,
      capacity: classItem.capacity !== null && classItem.capacity !== undefined ? classItem.capacity : null,
      currentCount: classItem.currentCount !== null && classItem.currentCount !== undefined ? classItem.currentCount : null,
      remarks: classItem.remarks || '',
      enabled: classItem.enabled !== undefined ? classItem.enabled : true,
    });
    
    setIsEditDialogOpen(true);
  };

  // 打开删除对话框
  const openDeleteDialog = (classItem: Class) => {
    setSelectedClass(classItem);
    setIsDeleteDialogOpen(true);
  };

  // 打开添加对话框
  const openAddDialog = () => {
    addForm.reset({
      name: '',
      grade: '',
      capacity: null,
      currentCount: null,
      remarks: '',
      enabled: true,
    });
    setIsAddDialogOpen(true);
  };

  // 打开分配教师对话框
  const openAssignTeacherDialog = (classItem: Class) => {
    setSelectedClass(classItem);
    setSelectedTeacherId('');
    setIsAssignTeacherDialogOpen(true);
  };

  // 分配教师
  const handleAssignTeacher = async () => {
    if (!selectedClass || !selectedTeacherId) {
      toast({
        title: '请选择教师',
        description: '请先选择要分配的教师',
        variant: 'destructive',
      });
      return;
    }
    
    const classId = selectedClass.id;
    const teacherId = parseInt(selectedTeacherId);
    console.log('分配教师参数:', { classId, teacherId });
    
    setLoading(true);
    try {
      const result = await assignTeacherToClass(classId, teacherId);
      console.log('分配教师结果:', result);
      
      fetchClasses();
      setIsAssignTeacherDialogOpen(false);
      
      toast({
        title: '分配成功',
        description: `已成功为 ${selectedClass.grade}${selectedClass.name} 分配班主任`,
      });
    } catch (error: any) {
      console.error('分配教师失败:', error);
      if (error.response) {
        console.error('错误响应数据:', error.response.data);
        console.error('错误状态码:', error.response.status);
      }
      
      toast({
        title: '分配失败',
        description: error.response?.data?.message || '无法分配教师，请稍后重试',
        variant: 'destructive',
      });
    } finally {
      setLoading(false);
    }
  };

  // 渲染教师选择项
  const renderTeacherOptions = () => {
    if (!teachers || teachers.length === 0) {
      return <SelectItem value="no-teacher" disabled>暂无教师数据</SelectItem>;
    }
    
    return teachers.map((teacher) => (
      <SelectItem key={teacher.id} value={String(teacher.id)}>
        {teacher.name}
      </SelectItem>
    ));
  };

  return (
    <FadeIn>
      <Toaster />
      <div className="container mx-auto py-6">
        <h1 className="text-2xl font-bold mb-6">班级管理</h1>
        
        {/* 搜索和添加按钮 */}
        <div className="flex justify-between mb-6">
          <div className="flex gap-2">
            <Input
              placeholder="搜索班级、年级或班主任..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="w-64"
              onKeyDown={(e) => e.key === 'Enter' && handleSearch()}
            />
            <Button onClick={handleSearch}>搜索</Button>
          </div>
          <Button onClick={openAddDialog}>
            添加班级
          </Button>
        </div>
        
        {/* 班级列表 */}
        <div className="rounded-md border">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>ID</TableHead>
                <TableHead>年级</TableHead>
                <TableHead>班级名称</TableHead>
                <TableHead>班主任</TableHead>
                <TableHead>容量</TableHead>
                <TableHead>当前人数</TableHead>
                <TableHead>备注</TableHead>
                <TableHead>创建时间</TableHead>
                <TableHead>操作</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {loading ? (
                <TableRow>
                  <TableCell colSpan={10} className="text-center py-10">
                    <RefreshCw className="h-6 w-6 animate-spin mx-auto" />
                    <p className="mt-2 text-sm text-gray-500">加载中...</p>
                  </TableCell>
                </TableRow>
              ) : classes.length === 0 ? (
                <TableRow>
                  <TableCell colSpan={10} className="text-center py-4">
                    暂无数据
                  </TableCell>
                </TableRow>
              ) : (
                classes.map((classItem) => (
                  <TableRow key={classItem.id}>
                    <TableCell>{classItem.id}</TableCell>
                    <TableCell>{classItem.grade}</TableCell>
                    <TableCell>{classItem.name}</TableCell>
                    <TableCell>{classItem.teacher ? classItem.teacher.name : '-'}</TableCell>
                    <TableCell>{classItem.capacity || '-'}</TableCell>
                    <TableCell>{classItem.currentCount || '-'}</TableCell>
                    <TableCell>{classItem.remarks || '-'}</TableCell>
                    <TableCell>{formatDate(classItem.createTime)}</TableCell>
                    <TableCell>
                      <div className="flex gap-2">
                        <Button 
                          variant="outline" 
                          size="sm"
                          onClick={() => openEditDialog(classItem)}
                        >
                          <Pencil className="h-4 w-4 mr-1" />
                          编辑
                        </Button>
                        <Button 
                          variant="outline" 
                          size="sm"
                          onClick={() => openAssignTeacherDialog(classItem)}
                        >
                          <UserPlus className="h-4 w-4 mr-1" />
                          分配班主任
                        </Button>
                        <Button 
                          variant="destructive" 
                          size="sm"
                          onClick={() => openDeleteDialog(classItem)}
                        >
                          <Trash className="h-4 w-4 mr-1" />
                          删除
                        </Button>
                      </div>
                    </TableCell>
                  </TableRow>
                ))
              )}
            </TableBody>
          </Table>
        </div>
        
        {/* 分页 */}
        {classes.length > 0 && (
          <div className="flex justify-between items-center mt-4">
            <div className="text-sm text-gray-500">
              共 {pagination.totalElements} 条记录，第 {pagination.page + 1}/{pagination.totalPages} 页
            </div>
            <div className="flex gap-2">
              <Button
                variant="outline"
                size="sm"
                onClick={() => handlePageChange(0)}
                disabled={pagination.first}
              >
                首页
              </Button>
              <Button
                variant="outline"
                size="sm"
                onClick={() => handlePageChange(pagination.page - 1)}
                disabled={pagination.first}
              >
                上一页
              </Button>
              <Button
                variant="outline"
                size="sm"
                onClick={() => handlePageChange(pagination.page + 1)}
                disabled={pagination.last}
              >
                下一页
              </Button>
              <Button
                variant="outline"
                size="sm"
                onClick={() => handlePageChange(pagination.totalPages - 1)}
                disabled={pagination.last}
              >
                末页
              </Button>
            </div>
          </div>
        )}
        
        {/* 添加班级对话框 */}
        <Dialog open={isAddDialogOpen} onOpenChange={setIsAddDialogOpen}>
          <DialogContent className="sm:max-w-[500px]">
            <DialogHeader>
              <DialogTitle>添加班级</DialogTitle>
              <DialogDescription>
                请填写班级信息，带 * 为必填项
              </DialogDescription>
            </DialogHeader>
            
            <Form {...addForm}>
              <form onSubmit={addForm.handleSubmit(handleAddClass)} className="space-y-4">
                <FormField
                  control={addForm.control}
                  name="grade"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>年级 *</FormLabel>
                      <FormControl>
                        <Input {...field} placeholder="例如：一年级、二年级" />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                
                <FormField
                  control={addForm.control}
                  name="name"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>班级名称 *</FormLabel>
                      <FormControl>
                        <Input {...field} placeholder="例如：一班、二班" />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                
                <FormField
                  control={addForm.control}
                  name="capacity"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>容量</FormLabel>
                      <FormControl>
                        <Input {...field} value={field.value?.toString() || ''} placeholder="班级容量" />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                
                <FormField
                  control={addForm.control}
                  name="currentCount"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>当前人数</FormLabel>
                      <FormControl>
                        <Input {...field} value={field.value?.toString() || ''} placeholder="班级当前人数" />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                
                <FormField
                  control={addForm.control}
                  name="remarks"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>备注</FormLabel>
                      <FormControl>
                        <Input {...field} placeholder="班级备注信息" />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                
                <DialogFooter>
                  <Button 
                    type="button" 
                    variant="outline" 
                    onClick={() => setIsAddDialogOpen(false)}
                  >
                    取消
                  </Button>
                  <Button type="submit" disabled={loading}>
                    {loading ? '提交中...' : '添加'}
                  </Button>
                </DialogFooter>
              </form>
            </Form>
          </DialogContent>
        </Dialog>
        
        {/* 编辑班级对话框 */}
        <Dialog open={isEditDialogOpen} onOpenChange={setIsEditDialogOpen}>
          <DialogContent className="sm:max-w-[500px]">
            <DialogHeader>
              <DialogTitle>编辑班级</DialogTitle>
              <DialogDescription>
                修改班级信息，带 * 为必填项
              </DialogDescription>
            </DialogHeader>
            
            <Form {...editForm}>
              <form onSubmit={editForm.handleSubmit(handleEditClass)} className="space-y-4">
                <FormField
                  control={editForm.control}
                  name="grade"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>年级 *</FormLabel>
                      <FormControl>
                        <Input {...field} placeholder="例如：一年级、二年级" />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                
                <FormField
                  control={editForm.control}
                  name="name"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>班级名称 *</FormLabel>
                      <FormControl>
                        <Input {...field} placeholder="例如：一班、二班" />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                
                <FormField
                  control={editForm.control}
                  name="capacity"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>容量</FormLabel>
                      <FormControl>
                        <Input {...field} value={field.value?.toString() || ''} placeholder="班级容量" />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                
                <FormField
                  control={editForm.control}
                  name="currentCount"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>当前人数</FormLabel>
                      <FormControl>
                        <Input {...field} value={field.value?.toString() || ''} placeholder="班级当前人数" />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                
                <FormField
                  control={editForm.control}
                  name="remarks"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>备注</FormLabel>
                      <FormControl>
                        <Input {...field} placeholder="班级备注信息" />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                
                <DialogFooter>
                  <Button 
                    type="button" 
                    variant="outline" 
                    onClick={() => setIsEditDialogOpen(false)}
                  >
                    取消
                  </Button>
                  <Button type="submit" disabled={loading}>
                    {loading ? '提交中...' : '保存'}
                  </Button>
                </DialogFooter>
              </form>
            </Form>
          </DialogContent>
        </Dialog>
        
        {/* 删除确认对话框 */}
        <Dialog open={isDeleteDialogOpen} onOpenChange={setIsDeleteDialogOpen}>
          <DialogContent className="sm:max-w-[425px]">
            <DialogHeader>
              <DialogTitle>删除班级</DialogTitle>
              <DialogDescription>
                您确定要删除班级 "{selectedClass?.grade}{selectedClass?.name}" 吗？此操作不可撤销。
              </DialogDescription>
            </DialogHeader>
            <DialogFooter>
              <Button 
                type="button" 
                variant="outline" 
                onClick={() => setIsDeleteDialogOpen(false)}
              >
                取消
              </Button>
              <Button 
                variant="destructive" 
                onClick={handleDeleteClass} 
                disabled={loading}
              >
                {loading ? '删除中...' : '确认删除'}
              </Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>
        
        {/* 分配班主任对话框 */}
        <Dialog open={isAssignTeacherDialogOpen} onOpenChange={setIsAssignTeacherDialogOpen}>
          <DialogContent className="sm:max-w-[425px]">
            <DialogHeader>
              <DialogTitle>分配班主任</DialogTitle>
              <DialogDescription>
                为班级 "{selectedClass?.grade}{selectedClass?.name}" 分配班主任
              </DialogDescription>
            </DialogHeader>
            
            <div className="py-4">
              <div className="space-y-2">
                <label className="text-sm font-medium">选择教师</label>
                <Select
                  value={selectedTeacherId}
                  onValueChange={setSelectedTeacherId}
                >
                  <SelectTrigger>
                    <SelectValue placeholder="选择教师" />
                  </SelectTrigger>
                  <SelectContent>
                    {renderTeacherOptions()}
                  </SelectContent>
                </Select>
                <p className="text-sm text-gray-500 mt-1">
                  当前班主任: {selectedClass?.teacher ? selectedClass.teacher.name : '未分配'}
                </p>
              </div>
            </div>
            
            <DialogFooter>
              <Button 
                type="button" 
                variant="outline" 
                onClick={() => setIsAssignTeacherDialogOpen(false)}
              >
                取消
              </Button>
              <Button 
                type="button" 
                onClick={handleAssignTeacher}
                disabled={loading || !selectedTeacherId}
              >
                {loading ? '提交中...' : '确认分配'}
              </Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>
      </div>
    </FadeIn>
  );
}
